import React, { useState, useEffect, useRef } from 'react';
import { io } from 'socket.io-client';
import MessageList from './MessageList';
import UserList from './UserList';
import InputBox from './InputBox';
import './Chat.css';

const socket = io('http://localhost:3001');

function Chat() {
  const [messages, setMessages] = useState([]);
  const [users, setUsers] = useState([]);
  const [currentUser, setCurrentUser] = useState(null);
  const [inputMessage, setInputMessage] = useState('');
  const messagesEndRef = useRef(null);

  useEffect(() => {
    // 监听消息
    socket.on('message', (message) => {
      setMessages(prev => [...prev, message]);
    });
    
    // 监听消息撤回
    socket.on('messageRecalled', (recalledMessage) => {
      setMessages(prev => prev.map(msg => 
        msg.id === recalledMessage.id ? recalledMessage : msg
      ));
    });

    // 监听用户加入
    socket.on('userJoined', (data) => {
      setUsers(prev => {
        // 检查用户是否已存在
        if (!prev.some(user => user.id === data.user.id)) {
          return [...prev, data.user];
        }
        return prev;
      });
      setMessages(prev => [...prev, { 
        type: 'system',
        username: '系统', 
        message: data.message,
        timestamp: new Date()
      }]);
    });

    // 监听用户离开
    socket.on('userLeft', (data) => {
      setUsers(prev => prev.filter(user => user.id !== data.user.id));
      setMessages(prev => [...prev, { 
        type: 'system',
        username: '系统', 
        message: data.message,
        timestamp: new Date()
      }]);
    });

    // 监听用户列表更新
    socket.on('userList', (userList) => {
      setUsers(userList);
    });

    return () => {
      socket.off('message');
      socket.off('userJoined');
      socket.off('userLeft');
      socket.off('messageRecalled');
      socket.off('userList');
    };
  }, []);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const sendMessage = (e) => {
    e.preventDefault();
    if (inputMessage.trim() && currentUser) {
      socket.emit('message', { 
        message: inputMessage,
        userId: currentUser.id
      });
      setInputMessage('');
    }
  };

  // 处理消息撤回
  const handleRecallMessage = (messageId) => {
    socket.emit('recallMessage', messageId);
  };

  // 处理用户选择
  const handleUserSelect = (user) => {
    if (user.id !== currentUser?.id) {
      setCurrentUser(user);
      socket.emit('join', user);
    }
  };

  // 处理添加用户
  const handleAddUser = (username) => {
    const newUser = {
      id: Date.now().toString(),
      username
    };
    socket.emit('join', newUser);
  };

  return (
    <div className="chat-container">
      <header className="chat-header">
        <h1>实时聊天</h1>
        <div className="current-user">
          当前用户: <strong>{currentUser?.username || '未选择'}</strong>
        </div>
      </header>
      
      <div className="chat-content">
        <div className="chat-sidebar">
          <h2>在线用户</h2>
          <UserList 
            users={users} 
            currentUser={currentUser} 
            onUserSelect={handleUserSelect}
            onAddUser={handleAddUser}
          />
        </div>
        
        <div className="chat-main">
          <MessageList 
            messages={messages} 
            currentUser={currentUser} 
            onRecallMessage={handleRecallMessage}
          />
          <div ref={messagesEndRef} />
          <InputBox 
            inputMessage={inputMessage}
            setInputMessage={setInputMessage}
            sendMessage={sendMessage}
            users={users}
            currentUser={currentUser}
          />
        </div>
      </div>
    </div>
  );
}

export default Chat;